import {
  _decorator,
  Camera,
  Collider2D,
  Color,
  Component,
  director,
  Input,
  input,
  instantiate,
  Label,
  Node,
  Prefab,
  Sprite,
  tween,
} from "cc";
import { Pin } from "./Pin";
import { Circle } from "./Circle";
const { ccclass, property } = _decorator;

@ccclass("GameManager")
export class GameManager extends Component {
  @property(Prefab)
  public pinPrefab: Prefab = null;

  @property(Node)
  public circleNode: Node = null;

  @property(Node)
  public pinPosition1: Node = null;

  @property(Node)
  public pinPosition2: Node = null;

  @property(Node)
  public pinPosition3: Node = null;

  @property(Node)
  public bgNode: Node = null;

  @property(Label)
  public scoreLabel: Label = null;

  @property(Camera)
  public camera: Camera = null;

  @property
  public targetOrthoHeight: number = 500;

  @property(Color)
  public targetColor: Color = new Color();

  public score: number = 0;

  public isGameOver: boolean = false;

  @property
  public moveDuration: number = 0.1;

  public currPin: Pin = null;

  private static _instance: GameManager = null;

  public static getInstance(): GameManager {
    return GameManager._instance;
  }

  protected onLoad() {
    GameManager._instance = this;
    // const collider = this.node.getComponent(Collider2D);
    // if (collider) {
    //   collider.on(Collider2D.EventType.END_CONTACT, this.onEndContact, this);
    // }
    input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
  }
  protected start() {
    this.pinSpawn();
  }

  protected update(deltaTime: number) {}

  public updateScore() {
    this.score += 1;
    this.scoreLabel.string = this.score.toString();
  }

  //   public onEndContact(other: Collider2D, self: Collider2D) {}
  public onTouchStart() {
    if (this.isGameOver) return;
    this.currPin.moveTo(
      this.pinPosition3.position,
      this.moveDuration,
      this.circleNode
    );
    this.pinSpawn();
  }

  public pinSpawn() {
    const pinNode = instantiate(this.pinPrefab);
    this.node.addChild(pinNode);
    pinNode.setPosition(this.pinPosition1.position);

    this.currPin = pinNode.getComponent(Pin);
    if (this.currPin) {
      this.currPin.moveTo(this.pinPosition2.position, this.moveDuration, null);
    }
  }

  public gameOver() {
    // 游戏结束逻辑
    this.isGameOver = true;
    this.circleNode.getComponent(Circle).stopRotate();
    // 放大
    // 关于颜色的渐变动画可以使用插值 Color.lerp() 方法
    tween(this.camera)
      .to(
        1,
        { orthoHeight: this.targetOrthoHeight, clearColor: this.targetColor },
        { easing: "smooth" }
      )
      .start();
    // tween(this.bgNode.getComponent(Sprite))
    //   .to(1, { color: this.targetColor })
    //   .start();

    // 重新加载关卡
    this.scheduleOnce(() => {
      director.loadScene("game");
    }, 2);
  }
}
